<?php

namespace App\Http\Controllers\Alipay;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Models\Bill\BillCustBuyLog;  //会员最后一次购买记录表

use App\Models\Customer\Customer;  //会员主表

use App\Models\ConfigureFunction;  //配置信息

use App\Models\Alipay\AlipayCustomer; //支付宝会员主表

use App\Service\Alipay\AlipayRequestService;

use Illuminate\Support\Facades\Redis as Redis;

use App\Http\Controllers\Controller;

class AlipayOauthController extends Controller
{


    /**
     * 支付宝页面授权入口
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function send(Request $request)
    {

        $host = $request->getSchemeAndHttpHost();
        $redirect_url = $request->input('redirect_url', $host . '/wap/index.html');
        $session_id = session_id();
        $custID   = $request->cookie('WANSONSHOP_IDENTIFIER');

        Redis::setex( 'G_UNION_LOGIN_REDIRECT_URL' . $session_id, 86400, urlencode($redirect_url));
        $cust_info = redisTransformation(Redis::get($session_id . 'LOGINSESSION'));

        /**
         * 1. 存在用户登录状态延长保存用户信息
         * 2. 不存在用户登录信息页面授权保存用户信息
         */
        if ( !empty($cust_info['alipay_uuid']) && !empty($cust_info['pcustID']) && $custID) {

            $login_session = redisTransformation(Redis::get($session_id . 'LOGINSESSION'));
            $sess_log = redisTransformation(Redis::get($session_id . 'CUST_BUY_LOG'));

            //延长保存在redis和cookie的会员信息
            Redis::setex($session_id . 'EBSIG_ALIPAY_UUID', 630720000, redisTransformation($login_session['alipay_uuid'], 'set',630720000));
            Redis::setex($session_id . 'LOGINSESSION', 630720000, redisTransformation($login_session, 'set',630720000));
            Redis::setex($session_id . 'CUST_BUY_LOG', 630720000, redisTransformation($sess_log, 'set',630720000));

            return redirect()->to($redirect_url)->withCookie(cookie('WANSONSHOP_IDENTIFIER', $custID, 10512000));

        } else {

            $app_id = ConfigureFunction::getConfigureField(42, 'app_id');
            $http_array = [
                'app_id' => $app_id,
                'scope' => 'auth_user,auth_base',
                'redirect_uri' => $host . '/lar/alipay/auth/notify'
            ];

            $requestURL = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?' . http_build_query( $http_array );

            return redirect()->to($requestURL);

        }

    }


    /**
     * 支付宝授权后异步通知
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function notify( Request $request )
    {

        $auth_code = $request->input('auth_code', '');
        $session_id = session_id();
        $redirect_url = urldecode(Redis::get( 'G_UNION_LOGIN_REDIRECT_URL' . $session_id));

        if ( empty($auth_code) ) {
            return redirect()->to($redirect_url);
        }

        $client = new AlipayRequestService();

        //获取授权后access_token
        $client->method = 'alipay.system.oauth.token';
        $client->biz_content = [
            'code' => $auth_code,
            'grant_type' => 'authorization_code'
        ];
        $client->response_key = 'alipay_system_oauth_token_response';
        $res = $client->query();
        if ($res['code'] != 200) {
            return redirect()->to($redirect_url);
        }

        //获取会员详细信息
        $client->auth_token = $res['data']['access_token'];
        $client->method = 'alipay.user.info.share';
        $client->biz_content = '';
        $client->response_key = 'alipay_user_info_share_response';
        $user_info = $client->query();
        if ($user_info['code'] != 200 ) {
            return redirect()->to($redirect_url);
        }

        $user_info_res = $this->saveUserInfo($user_info['data']);
        if ( $user_info_res ) {
            Redis::setex( 'ALIPAY_USER_ID_' . $session_id, 30*24*3600, $user_info_res['user_id']);
            return redirect()->to($redirect_url)->withCookie(cookie('EBSIG_ALIPAY_UUID', $user_info_res['user_id'], 10512000))->withCookie(cookie('WANSONSHOP_IDENTIFIER', $user_info_res['custID'], 10512000));
        } else {
            return redirect()->to($redirect_url);
        }


    }



    /**
     * 处理会员信息
     * @param $user_info array 支付宝会员信息
     * @param int $login_timeout int 时间戳
     * @return
     */
    public function saveUserInfo( $user_info, $login_timeout = 630720000 ) {

        $session_id = session_id();

        $alipay_customer = AlipayCustomer::where(['alipay_user_id' => $user_info['user_id']])->first();

        if( empty($alipay_customer) ) {

            $alipay_customer = new AlipayCustomer();

            $alipay_customer_array = [
                'uuid' => makeUuid(),
                'timeStamp' => Carbon::now(),
                'createTime' => Carbon::now(),
                'creator' => 'alipay_oauth',
                'alipay_user_id' => $user_info['user_id'],
                'pcustID' => 0,
                'follow' => 0,
                'mobile' => 0,
            ];

            if ( isset($user_info['province']) ) {
                $alipay_customer_array['province'] = $user_info['province'];
            }
            if ( isset($user_info['city']) ) {
                $alipay_customer_array['city'] = $user_info['city'];
            }
            if ( isset($user_info['gender']) ) {
                if( $user_info['gender'] == 'm' || $user_info['gender'] == 'M') {
                    $alipay_customer_array['sex'] = 1;
                }
                if( $user_info['gender'] == 'f' || $user_info['gender'] == 'F') {
                    $alipay_customer_array['sex'] = 2;
                }
            }
            if ( isset($user_info['avatar']) ) {
                $alipay_customer_array['avatar'] = $user_info['avatar'];
            }

            $alipay_customer->insert( $alipay_customer_array );

        } else {
            //更新支付宝会员信息
            $alipay_customer_array = [
                'avatar' => $user_info['avatar'],
                'nick_name' => $user_info['nick_name'],
            ];
            $alipay_customer->save( $alipay_customer_array );
        }

        if( empty($alipay_customer->pcustID) ) {
            Redis::setex($session_id . 'ALIPAY_CUSTOMER_UUID', 360000, redisTransformation($alipay_customer->uuid, 'set',360000));
            Redis::setex($session_id . 'EBSIG_ALIPAY_UUID', $login_timeout, redisTransformation($alipay_customer->uuid, 'set',$login_timeout));
            return null;
        }

        //查询会员信息并更新登录状态
        $customer_array = Customer::find($alipay_customer->pcustID);
        if ( empty($customer_array) ) {
            return null;
        }

        $login_session['pcustID'] = $customer_array['pcustID'];
        $login_session['custID'] = $customer_array['custID'];
        $login_session['mobile'] = $customer_array['mobile'];
        $login_session['alipay_uuid'] = $user_info['user_id'];
        $login_session['guest'] = 0;

        Redis::setex($session_id . 'LOGINSESSION', $login_timeout, redisTransformation($login_session, 'set',$login_timeout));

        //查询会员最后一次购买记录
        $last_buy_log = BillCustBuyLog::find($customer_array['pcustID']);

        if ( !empty($last_buy_log) ) {
            $last_buy_log_array = [
                'pcustID' => $last_buy_log->pcustID,
                'deliverID' => $last_buy_log->deliverID,
                'send_region_id' => $last_buy_log->send_region_id,
                'sendTypeID' => $last_buy_log->sendTypeID,
                'payTypeID' => $last_buy_log->payTypeID,
                'pay_type' => $last_buy_log->pay_type,
                'payment_method_id' => $last_buy_log->payment_method_id,
                'invoiceID' => $last_buy_log->invoiceID,
                'send_time_id' => $last_buy_log->sendTimeID,
                'extend_1' => $last_buy_log->extend_1,
                'extend_2' => $last_buy_log->extend_2,
                'extend_3' => $last_buy_log->extend_3,
                'extend_4' => $last_buy_log->extend_4,
                'extend_5' => $last_buy_log->extend_5,
                'extend_6' => $last_buy_log->extend_6
            ];

            Redis::setex($session_id . 'CUST_BUY_LOG', $login_timeout, redisTransformation($last_buy_log_array, 'set',$login_timeout));
        }

        //客户未登录时的购物车
        $old_bill_array = redisTransformation(Redis::get( $session_id . 'shop_cart'));
        if ( empty($old_bill_array) ){
            return [ 'user_id' => urlencode($user_info['user_id']), 'custID'=>  urlencode($customer_array['custID'])];
        }

        $old_cart =& $old_bill_array['goods'];

        if (empty($old_cart)){
            return [ 'user_id' => urlencode($user_info['user_id']), 'custID'=>  urlencode($customer_array['custID'])];
        }

        /**
         * 在客户登录时把未登录时的购物车合并到客户上次登录时的购物车。
         * 同时删除未登录时的购物车
         * 客户上次登录时的购物车数据
         */
        $bill_array = redisTransformation(Redis::get('shop_cart_' . $customer_array['pcustID']));
        if (!$bill_array) {

            $bill_array = [
                'bill_no' => null,

                'bill_status' => 0,

                'change_time' => null,

                'message' => null,

                'goods' => array(),

                'master' => array()
            ];

        }

        //合并普通商品
        if (isset($old_cart['general']) && !empty($old_cart['general'])) {
            foreach ($old_cart['general'] as $postID => &$goods) {
                if (isset($bill_array['goods']['general'][$postID])) {
                    $bill_array['goods']['general'][$postID]['goods_amount'] += $goods['goods_amount'];
                } else {
                    $bill_array['goods']['general'][$postID] = $goods;
                }
            }
        }

        $bill_array['change_time'] = time();
        Redis::setex('shop_cart_' . $customer_array['pcustID'], 360000, redisTransformation($bill_array, 'set', 360000));
        Redis::del($session_id . 'shop_cart');

        return  [ 'user_id' => urlencode($user_info['user_id']), 'custID'=>  urlencode($customer_array['custID'])];

    }






}